package main

import (
	"alex/sensorfingerprint/pixel"
	"alex/sensorfingerprint/data"
	"fmt"
	"os"
	"strings"
	"code.google.com/p/go.image/bmp"
	_"image/color"
)

//full path to the fingerprint image folder
var (
	//path string = "/Users/AlexZ/"
	path1 string = "/Users/AlexZ/Uni/biometrische/databases/finger/2009/finger_uru4000/"
	path2 string = "/Users/AlexZ/Uni/biometrische/databases/finger/2013/uru4000_1/"
	//path string = "/Users/AlexZ/Uni/stuff/zri/"
	pix [][]data.PixelData
	threshold int = 1000
)

func main() {
	fmt.Println("Opening Images...")
	openImages(path1, true)
	fmt.Println("Comparing Images...")
	openImages(path2, false)
}

func openImages(pathToImages string, createFingerprint bool) {
	//Opening directory
	directory, err := os.Open(pathToImages)
	errHandling(err)
	defer directory.Close()

	out, err := os.Create("/Users/AlexZ/Uni/biometrische/outt1.txt")
	errHandling(err)
	defer out.Close()

	//Scanning all directory files
	files, err := directory.Readdir(0)
	errHandling(err)

	//Iterating over those files
	for _, file := range files {
		//Filtering Process - only *.bmp files are processed
		if file.Mode().IsRegular() && strings.HasSuffix(file.Name(), ".bmp") {
			name := pathToImages + file.Name()
			fi, err := os.Open(name)
			errHandling(err)
			img, err := bmp.Decode(fi)
			errHandling(err)

			if createFingerprint {
				if pix == nil {
					// 2 dimensional array initialisation - the lvl of stupidity know no bounds...
					pix = make([][] data.PixelData, img.Bounds().Max.X)
					for i := range pix {
						pix[i] = make([] data.PixelData, img.Bounds().Max.Y)
					}
				}
				pixel.DetectSurroundingPixels(img, pix)
				fi.Close()
			} else {
				mask, val := pixel.CompareImageWithFingerprint(img, pix, threshold)
				out.WriteString(fmt.Sprintf("File: %v - Stimmt: %v\n", file.Name(), val/mask))
			}
		}
	}
	debugSave("/Users/AlexZ/Uni/biometrische/f2009t6.txt")
}

func debugSave(filename string) {
	fo, err := os.Create(filename)
	errHandling(err)
	for i := range pix {
		for j := range pix {
			if pix[i][j].Count > threshold {
				fo.WriteString(fmt.Sprintf("Stuck: %+v - Coord %+v %+v\n", pix[i][j], i, j))
			}
		}
	}
	fo.Close()
}

func errHandling(err error) {
	if err != nil {
		fmt.Println(err)
	}
}
